<template>
  <div class="">
    <!-- 条件筛选-----查询 -->
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div>
          <el-form-item>
            <el-input v-model="uid" clearable placeholder="用户ID" style="width: 120px;" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="key" clearable placeholder="用户名/姓名" style="width: 550px;" />
          </el-form-item>
          <el-form-item>
            <label>币种：</label>
            <el-select v-model="coinid" placeholder="币种">
              <el-option label="全部" :value="0" />
              <el-option v-for="item in coinList" :disabled="item.coinid == 3" :label="item.coinname"
                :value="item.coinid" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <label>交易类型：</label>
            <el-select v-model="tradetype" placeholder="交易类型" style="width: 180px;">
              <el-option v-for="item in Object.keys(tradetypeList)" :label="tradetypeList[item]" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="dateTime" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
        </div>
        <div>
          <el-form-item>
            <div class="flex">
              <el-button type="primary" :loading="createWithdLoading" @click="createWithd">生成打款订单</el-button>
              <el-button type="primary" :loading="exportLoading" @click="doExport">导出Excel</el-button>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!-- 列表数据 -->
    <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
      <el-table-column prop="uid" label="用户ID" align="center" width="80" />
      <el-table-column prop="username" label="用户信息" width="200" align="center">
        <template slot-scope="{row}">
          <div>账号：{{ row.username }}</div>
          <div>姓名：{{ row.truename }}</div>
          <div>手机号：{{ row.username }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="订单用户" width="150" align="center">
        <template slot-scope="{row}">
          <div>姓名：{{ row.orderTruname }}</div>
          <div>手机号：{{ row.orderPhone }}</div>
          <div>入账金额：{{ row.orderAmtStr }}</div>
          <div>服务商身份：{{ row.dlsStr }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="分公司" width="150" align="center">
        <template slot-scope="{row}">
          <div>姓名：{{ row.compyName }}</div>
          <div>手机号：{{ row.compyPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="bankname" label="收款信息" width="200" align="center">
        <template slot-scope="{row}">
          <div>银行名称：{{ row.bankname }}</div>
          <div>支行名称：{{ row.bankname2 }}</div>
          <div>银行卡号：{{ row.bandkcard }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="tradetype" label="交易类型" width="150" align="center">
        <template v-if="tradetypeList" slot-scope="scope">
          <el-tag>{{ tradetypeList[scope.row.tradetype] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="coinid" width="120" label="币种" align="center">
        <template slot-scope="{row}">
          <span v-if="row.coinid == item.coinid" v-for="item in coinList">{{ item.coinname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="income" label="金额" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.income > 0">+{{ scope.row.income }}</span>
          <span v-if="scope.row.payout > 0">-{{ scope.row.payout }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="beforbalance" label="交易前余额" align="center" width="150" />
      <el-table-column prop="afterbalance" label="交易后余额" align="center" width="150" />
      <el-table-column prop="orderStr" label="业务类型" align="center" width="100" />
      <!-- <el-table-column prop="orderSource" label="订单来源/备注" show-overflow-tooltip align="center" width="100">
        <template slot-scope="{row}">
          <el-link v-if="row.orderSource != ''" type="primary" @click="openOrderInfo(row)">查看</el-link>
          <div v-else type="primary">无</div>
        </template>
      </el-table-column> -->
      <el-table-column prop="state" label="交易状态" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1">已完成</span>
          <span v-if="scope.row.state == 0">未完成</span>
        </template>
      </el-table-column>
      <el-table-column prop="tradedescription" label="摘要" align="center" width="160" />
      <el-table-column prop="createtime" label="交易时间" align="center" width="160" />
      <el-table-column label="操作" width="150" fixed="right" align="center">
        <template slot-scope="{row}">
          <el-button v-if="[11, 12, 13].includes(row.tradetype)" size="mini" type="primary"
            @click="openOrderInfo(row)">订单详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-form :inline="true" style="padding-top: 10px;">
      <el-form-item v-if="total != null">
        <div class="flex">
          <div style="font-size: 20px;font-weight: bold;">统计:</div>
          <div style="margin-left: 20px;">【新增额: {{ total.income }} 】</div>
          <div style="margin-left: 20px;">【减少额: {{ total.payout }} 】</div>
        </div>
      </el-form-item>
    </el-form>
    <!-- 分页 -->
    <div class="block " style="padding-top: 20px;">
      <el-pagination background :current-page="pageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="idx => { pageSize = idx }"
        @current-change="idx => { pageIndex = idx }" />
    </div>

    <!-- 订单详情 -->
    <digOrserInfo v-if="modalStatus == 1" :orderid="currentId" />
  </div>
</template>

<script>
import { userbalancerecord, UserBalanceRecordExcel, CreateWithdrawApply } from '@/api/users.js'
import { getEnumList } from '@/utils/auth.js'
import { GetEnum, coinlist } from "@/api/ctrls.js";
import { formatDate } from '@/utils/index.js'
import digOrserInfo from '../../components/digOrderInfo.vue'
import { mapState } from 'vuex'
export default {
  name: 'Name',
  components: { digOrserInfo },
  data() {
    return {
      dateTime: [], // 时间查询
      uid: '',
      key: '',
      stime: '', // 开始时间 2022-01-01
      etime: '', // 结束时间
      coinid: '-1', // 币种ID
      tradetype: '0',
      stype: 0,


      listLoading: false,
      tableData: [],
      totalCount: 0,
      pageIndex: 1,
      pageSize: 20,
      total: {},


      tradetypeList: {},
      coinList: [],

      modalStatus: 0, // 打开组件弹窗参数
      currentInfo: {}, // 当前用户信息
      currentId: 0,

      exportLoading: false, // 导出loading
      createWithdLoading: false, // 生成loading
    }
  },
  computed: {
    // ...mapState({
    //   tradetypeList: state => state.user.enumList["TradeType"]
    // })
  },
  watch: {
    pageIndex(val) {
      console.log(val)
      this.getData()
    },
    pageSize(val) {
      console.log(val)
      this.getData()
    },
    modalStatus(val) {
      this.getData()
    }
  },
  async created() {
    this.uid = this.$route.query.userid || ''
    this.coinid = this.$route.query.coinid || 0
    this.tradetype = this.$route.query.tradetype || '0'
    this.dateTime = this.$route.query.dateTime || []
    if (this.$route.query.type == 'day') {
      this.coinid = 1;
      this.tradetype = '6';
      this.dateTime[0] = formatDate(new Date(), 'yyyy-MM-dd')
      this.dateTime[1] = formatDate(new Date(), 'yyyy-MM-dd')
    }
    if (this.$route.query.type == '2') {
      this.coinid = 1;
      this.tradetype = '6';
    }
  },
  async mounted() {
    this.getData()
    this.GetEnum();
    this.GetCoin();
  },
  methods: {
    // 获取枚举
    async GetEnum() {
      const res = await GetEnum();
      this.tradetypeList = res.data['TradeType']
      // console.log('币种：：', this.coinList);
    },
    // 获取币种
    async GetCoin() {
      const res = await coinlist();
      this.coinList = res;
    },
    /**打开来源/备注弹窗 */
    openOrderInfo(info) {
      this.currentId = info.tid;
      this.modalStatus = 1;
    },
    /////////////////////// 导出报表  ///////////////////////
    // 导出报表
    async doExport() {
      this.exportLoading = true;
      const res = await UserBalanceRecordExcel({
        uid: this.uid,
        key: this.key,
        coinid: this.coinid,
        stime: this.dateTime ? this.dateTime[0] : '',
        etime: this.dateTime ? this.dateTime[1] : '',
        tradetype: this.tradetype,
      });
      this.exportLoading = false;
      if (res) {
        console.log('导出网络数据：：', res);
        // 文件名
        const fileName = "资金记录列表.xlsx";
        // 处理导出数据并下载
        this.handleExcel(res, fileName);
      }
    },
    /**转换数据类型  下载Excel报表 */
    handleExcel(data, fileName) {
      //转换数据类型
      const xlsx = "application/vnd.ms-excel;charset=utf-8";
      const blob = new Blob([data], { type: xlsx });
      console.log(blob);

      // 转换完成，创建一个a标签用于下载
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = URL.createObjectURL(blob);
      a.setAttribute("download", fileName);
      document.body.appendChild(a);
      a.click();
      a.remove();
    },
    async onSearch() {
      this.pageIndex = 1
      this.getData()
    },
    // 生成打款订单
    async createWithd() {
      this.createWithdLoading = true;
      const { success, msg } = await CreateWithdrawApply({
        uid: this.uid,
        key: this.key,
        coinid: this.coinid,
        stime: this.dateTime ? this.dateTime[0] : '',
        etime: this.dateTime ? this.dateTime[1] : '',
        tradetype: this.tradetype,
      });
      this.createWithdLoading = false;
      if (success) {
        const confirm = await this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
        if (confirm == 'confirm') {
          this.copyToClipboard(msg);
        }
      }
    },
    copyToClipboard(text) {
      // 创建<textarea>元素并设置其值
      var textarea = document.createElement('textarea');
      textarea.value = text;

      // 将<textarea>元素插入到文档中
      document.body.appendChild(textarea);

      // 选中<textarea>元素中的文本
      textarea.select();

      // 复制选中的文本到剪贴板
      try {
        var isSuccess = document.execCommand('copy');
        var message = isSuccess ? '成功复制到剪贴板' : '无法复制到剪贴板';
        this.$message({
          message: message,
          type: isSuccess ? 'success' : 'error'
        })
      } catch (err) {
        console.error('复制操作失败', err);
      }

      // 删除插入的<textarea>元素
      document.body.removeChild(textarea);
    },
    // 获取数据
    async getData() {
      this.listLoading = true
      const { list, totalCount, _total } = await userbalancerecord({
        uid: this.uid,
        key: this.key,
        coinid: this.coinid,
        stime: this.dateTime ? this.dateTime[0] : '',
        etime: this.dateTime ? this.dateTime[1] : '',
        tradetype: this.tradetype,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      })
      this.totalCount = totalCount
      this.total = _total
      list.forEach(element => {
        element.createtime = element.createtime.replace('T', ' ')
        this.tableData.push(element)
      })
      this.tableData = list
      this.listLoading = false
    }
  }
}
</script>

<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}
</style>
